package com.asset.web.interceptor;

import com.asset.pojo.User;
import com.asset.util.AssetExceptionEnum;
import com.asset.util.AssetManageException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import sun.plugin.liveconnect.SecurityContextHelper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 11725
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /** 记录 user 信息的 ThreadLocal 对象 */
    private static final ThreadLocal<User> USER_INFO_STORE = new ThreadLocal<>();

    /** user's info session name */
    private static final String USER_INFO = "USER_INFO";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal());

        if (user != null) {
            // 保存登录用户账户信息
            USER_INFO_STORE.set(user);
        } else {
            log.info("[login:interceptor] - 用户未登录");
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除与线程绑定的数据
        USER_INFO_STORE.remove();
    }

    public static User getUser() {
        User login = USER_INFO_STORE.get();

        if (login != null) {
            return login;
        }

        throw new AssetManageException(AssetExceptionEnum.USER_NOT_LOGGED_IN);
    }
}
